﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WinFormClient
{
    class MapXML2
    {
        #region namespace
        private string _namespace;
        public string NameSpace
        {
            get { return _namespace; }
            set { _namespace = value; }
        }
        #endregion

        #region class
        private string _className;
        public string ClassName
        {
            get { return _className; }
            set { _className = value; }
        }
        #endregion

        private string _classType;
        public string ClassType
        {
            get { return _classType; }
            set { _classType = value; }
        }

        #region
        private string _tableName;
        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }
        #endregion

        #region
        private string _domain;
        public string Domain
        {
            get { return _domain; }
            set { _domain = value; }
        }
        #endregion

        private string _assembly;
        public string Assembly
        {
            get { return _assembly; }
            set { _assembly = value; }
        }

        #region
        private List<KeyValuePair<string, string>> _listMapping;
        public List<KeyValuePair<string, string>> ListMapping
        {
            get { return _listMapping; }
            set { _listMapping = value; }
        }
        #endregion
        public MapXML2()
        {

        }

        public MapXML2(string nameSpace, string className, string tableName, List<KeyValuePair<string, string>> listMapping)
        {
            NameSpace = nameSpace;
            ClassName = className;
            TableName = tableName;
            ListMapping = listMapping;
        }




        public void Builder(bool getAll, bool getByPrimaryKey, bool getWithColumns, bool getWithUnlimited, bool create, bool delete, bool deleteByPrimaryKey, bool deleteWithColumns, bool deleteWithUnlimited, bool update, bool updateWithUnlimited)
        {
            string content
            = this.header() //头部
            + this.Alias()  //别名 
            + this.ResultMaps() //字段映射
            + this.ParameterMap() //存储过程的参数
            + Environment.NewLine
            + "  <" + _domain + ":statements>" + Environment.NewLine //操作语句
            + ((create) ? this.Create() : "") //创建
            + ((getAll) ? this.Select(KeyWhere(),"selectAll","") : "") //全选
            + ((update) ? this.Update(KeyWhere(), "updateAll", "") : "") //更新？？
            + ((delete) ? this.Delete(KeyWhere(), "deleteAll", "") : "") //删除 ？？
            + "  </" + _domain + ":statements>" + Environment.NewLine
            + "</" + _domain + ":sqlMap>"
            ;

            Tools.TextSaveToFile(content, "Xml", this._className + ".xml"); //保存XML文件
       }



        /// <summary>
        /// 生成Hearder
        /// </summary>
        /// <returns></returns>
        private string header()
        {
            return
                    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + System.Environment.NewLine
                + "<" + _domain + ":sqlMap namespace=\"" + _className + "\" xmlns=\"http://ibatis.apache.org/mapping\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >" + System.Environment.NewLine
            ;
        }

        private string Alias()
        {
            return
                    "  <" + _domain + ":alias>" + System.Environment.NewLine
                + "    <" + _domain + ":typeAlias alias=\"" + _className + "\" type=\"" + _classType + "\" assembly=\"" + _assembly  + "\" />" + System.Environment.NewLine
                + "  </" + _domain + ":alias>" + System.Environment.NewLine
            ;
        }

        private string ResultMaps()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(
                "  <" + _domain + ":resultMaps>" + Environment.NewLine
                + "    <" + _domain + ":resultMap id=\"" + _className + "Result\" class=\"" + _className + "\">" + Environment.NewLine
                );
            foreach (KeyValuePair<string, string> mapping in _listMapping)
            {
                sb.Append("      <" + _domain + ":result property=\"" + mapping.Key + "\" column=\"" + mapping.Value + "\" />" + Environment.NewLine);
            }
            sb.Append("    </" + _domain + ":resultMap>" + Environment.NewLine);
            sb.Append("  </" + _domain + ":resultMaps>" + Environment.NewLine);
            return sb.ToString();
        }

        private string ParameterMap()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(
                "  <" + _domain + ":parameterMaps>" + Environment.NewLine
                + "    <" + _domain + ":parameterMap id=\"" + this._tableName + "Parameter\" class=\"" + this._className + "\">" + Environment.NewLine
                );
            //暂时不做处理存储过程及参数
            //sb.Append("      <parameter property=\"" + map.PropertyName + "\" column=\"" + map.ColumnName + "\" />" + Environment.NewLine);
            sb.Append("    </" + _domain + ":parameterMap>" + Environment.NewLine);
            sb.Append("  </" + _domain + ":parameterMaps>" + Environment.NewLine);
            return sb.ToString();
        }

        private string Create()
        {
            //this._methods.Add(new Method("object", "Create", this._tableName + "_Create", "Model." + this._className, Tools.ParameterConvert(this._className), DataAccessMethod.ExecuteInsert));

            StringBuilder sb = new StringBuilder();
            sb.Append("    <" + _domain + ":insert id=\"" + _className + "_Create\"  parameterClass=\"" + this._className + "\" >" + Environment.NewLine);
            sb.Append("      INSERT INTO " + this._tableName + " (");
            int count = _listMapping.Count;
            for (int i = 0; i < count; i++) sb.Append(_listMapping[i].Value + ((i == (count - 1)) ? "" : ","));
            sb.Append(")");
            sb.Append(Environment.NewLine);
            sb.Append("      VALUES (");
            for (int i = 0; i < count; i++) sb.Append("#" + _listMapping[i].Key + "#" + ((i == (count - 1)) ? "" : ","));
            sb.Append(")" + Environment.NewLine);
            sb.Append("    </" + _domain + ":insert>" + Environment.NewLine);
            return sb.ToString();
        }

        private string EntryWhere()
        {

            if (_listMapping.Count == 0) return null;
            StringBuilder sb = new StringBuilder();
            sb.Append("      <dynamic prepend=\"WHERE\">" + Environment.NewLine);
            foreach (KeyValuePair<string,string> mapping in _listMapping)
            {
                sb.Append("          " + mapping.Value + " = #" + mapping.Key + "#" + Environment.NewLine);
            }            
            sb.Append("      </dynamic>" + Environment.NewLine);

            return sb.ToString();
        }

        private string KeyWhere()
        {
            //所有的实体类对象在数据库中都有一个ID，这里以ID来作为key
            StringBuilder sb = new StringBuilder();
            sb.Append("      <" + _domain + ":dynamic prepend=\"WHERE\">" + Environment.NewLine);
            sb.Append("         <" + _domain + ":isNotNull property=\"Id\" prepend=\"and\">" + Environment.NewLine);
            sb.Append("             <![CDATA[ID = #Id#]]" + Environment.NewLine);
            sb.Append("         </" + _domain + ":isNotNull>" + Environment.NewLine);
            sb.Append("      </" + _domain + ":dynamic>" + Environment.NewLine);

            return sb.ToString();
        }

        private string Select(string where, string id, string paramClass)
        {
            if (where == null) return "";

            StringBuilder sb = new StringBuilder();
            sb.Append(
                "    <" + _domain + ":select id=\"" + id + "\" resultMap=\"" + this._className + "Result\"" + ((String.IsNullOrEmpty(paramClass)) ? "" : (" parameterClass=\"" + paramClass + "\"")) + ">" + Environment.NewLine
                + "      SELECT * FROM " + this._tableName + Environment.NewLine
                );
            sb.Append(where);
            sb.Append("    </" + _domain + ":select>" + Environment.NewLine);

            return sb.ToString();
        }

        private string Delete(string where, string id, string paramClass)
        {
            if (String.IsNullOrEmpty(where)) return "";

            return
                  " <" + _domain + ":delete id=\"" + id + "\" parameterClass=\"" + paramClass + "\">" + Environment.NewLine
                + "     DELETE " + this._tableName + Environment.NewLine
                +               where
                + " </" + _domain + ":delete>" + Environment.NewLine
                ;
        }

        private string Update(string where, string id, string paramClass)
        {
            if (String.IsNullOrEmpty(where)) return "";

            StringBuilder sb = new StringBuilder();
            sb.Append(
                "    <" + _domain + ":update id=\"" + id + "\" parameterClass=\"" + paramClass + "\">" + Environment.NewLine
                + "        UPDATE " + this._tableName + Environment.NewLine
                + "        SET" + Environment.NewLine
                );
            int listLng = _listMapping.Count;
            for (int i = 0; i < listLng; i++)
            {

                sb.Append("          " + _listMapping[i].Value + " = #" + _listMapping[0].Key + "#" + ((i == (listLng - 1)) ? "" : ",") + Environment.NewLine);

            }
            sb.Append(where);
            sb.Append("    </" + _domain + ":update>" + Environment.NewLine);
            return sb.ToString();
        }
    }

}
